package com.cmos.um.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.cmos.um.beans.CtiMessage;
import com.cmos.um.beans.CtiMessageExtends;
import com.cmos.um.beans.CtiMessageTask;
import com.cmos.um.iservice.ICtiMessageSV;
import com.cmos.um.iservice.ICtiMessageTaskSV;
import com.cmos.um.iservice.IHumanTaskSV;
import com.cmos.um.utils.*;
import com.cmos.um.utils.http.RestClientHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Service
public class HumanTaskSVImpl implements IHumanTaskSV {

    private final static Logger logger = LoggerFactory.getLogger(HumanTaskSVImpl.class);


    @Autowired
    private ICtiMessageSV ctiMessageservice;

    @Autowired
    private RestClientHttpRequest clien;;

    @Autowired
    private ICtiMessageTaskSV CtiMessageTaskSV;

    /**
     * 渐进式外呼
     *
     * @param params
     * @return
     */
    @Override
    public Result save(JSONObject params) {
        JSONObject JsonParams = params.getJSONObject("params");
        String serviceId = JsonParams.getString("serviceId");//任务短号
        String XfServiceId = "000001" + WSContent.companyNo + "11" + serviceId;//拼接后新方的任务号
        String vccId = JsonParams.getString("vccId");//集团号
        JsonParams.put("scheduleKey", serviceId);

        String chargeNumber = "000002" + vccId + params.getString("chargeNumber");//计费分机号码
        JsonParams.put("agentRate", Integer.parseInt(JsonParams.getString("agentRate"))*10); // 外呼座席比，(外拨速率因子)为外呼线数与座席数的比例，单位是1%，取值范围50-1000，100为正常速度，大于100为加速，小于100为减速
        JsonParams.put("chargeNumber", chargeNumber);
        String beginTime1 = JsonParams.getString("beginTime1");
        String beginTime2 = JsonParams.getString("beginTime2");
        String beginTime3 = JsonParams.getString("beginTime3");
        //查询所有的cti
        List<CtiMessage> ctiMessage = ctiMessageservice.queryAll();

        //4.1 算法：寻找一个合适的CTI——目前采用平均分配的算法

        CtiMessage suit = null; // CC平台的相关数据——来自cti_message表
        suit = CtiAlgorithm.GetBastCti(ctiMessage);
        //b 记录分配的cti平台的IP地址
        String ctiIp = suit.getCtiIp();
        String ctiId = suit.getCtiId();
        JSONObject toCC = new JSONObject();
        if (!beginTime1.isEmpty() || !beginTime2.isEmpty() || !beginTime3.isEmpty()) {
            toCC.put("scheduleKey", serviceId); // 日程键，以任务号作为日程键
            toCC.put("vccId", vccId); // 集团号
            toCC.put("scheduleName", serviceId); // 日程名称
            toCC.put("updateKey", simpleSQL.cinNowTime()); // 更新标识
            WSRtnJsonCtx resultSchedule = clien.doPost(WSContent.vccUrl, ctiIp, "operateSchedule", WSContent._SAVE, toCC);
            if (!"0".equals(resultSchedule.getRescode())) {
                logger.error("增加日程失败，返回的信息为：" + resultSchedule.getResJsonObj());
                return ResultUtil.error("-9999", "增加日程失败");
            }
            for (int i = 1; i <= 3; i++) {
                toCC.clear();
                String beginTime = JsonParams.getString("beginTime" + i);
                String endTime = JsonParams.getString("endTime" + i);
                if (beginTime == null || beginTime.isEmpty()) {
                    continue;
                }
                if (endTime == null || endTime.isEmpty()) {
                    endTime = "23:59";
                }
                toCC.put("itemKey", serviceId + String.valueOf(i)); // 条目键
                toCC.put("scheduleKey", serviceId); // 日程键
                toCC.put("sunday", "1"); // 周日，0=无，1=有
                toCC.put("monday", "1"); // 周一，0=无，1=有
                toCC.put("tuesday", "1"); // 周二，0=无，1=有
                toCC.put("wednesday", "1"); // 周三，0=无，1=有
                toCC.put("thursday", "1"); // 周四，0=无，1=有
                toCC.put("friday", "1"); // 周五，0=无，1=有
                toCC.put("saturday", "1"); // 周六，0=无，1=有
                toCC.put("hourStart", beginTime.substring(0, 2)); // 开始小时
                toCC.put("hourEnd", endTime.substring(0, 2)); // 结束小时
                toCC.put("minuteStartminuteStart", beginTime.substring(3, 5)); // 开始分钟
                toCC.put("minuteEnd", endTime.substring(3, 5)); // 结束分钟
                toCC.put("updateKey", simpleSQL.cinNowTime()); // 更新标识
                WSRtnJsonCtx resultScheduleItem = clien.doPost(WSContent.vccUrl, ctiIp, "operateScheduleItem", WSContent._SAVE, toCC);

                if (!"0".equals(resultScheduleItem.getRescode())) {
                    logger.error("增加第" + i + "条日程条目失败，返回的信息为：" + resultSchedule.getResJsonObj());
                    return ResultUtil.error("-9999", "增加日程条目失败");
                }
            }
            WSRtnJsonCtx resultTask = clien.doPost(WSContent.servUrl, ctiIp, "operateHumanTask", WSContent._SAVE, JsonParams);
            if (!"0".equals(resultTask.getRescode())) {
                logger.error("新增任务失败，返回的信息为：" + resultTask.getResJsonObj());
                return ResultUtil.error("-9999", "增加任务失败");
            }
        } else {
            return ResultUtil.error("-9999", "日程信息为null");
        }
        //在cti_message_task表中记录分配的cti相关信息
        CtiMessageTask ctiMessageTask = new CtiMessageTask();
        ctiMessageTask.setTaskId(serviceId);//原始的任务id
        ctiMessageTask.setCtiId(ctiId);//分配到哪个cti
        ctiMessageTask.setTaskXfId(serviceId);//新方的任务id
        CtiMessageTaskSV.insertSelective(ctiMessageTask);
        //更新分配到任务的cti的任务数
        CtiMessage ctimessage = new CtiMessage();
        ctimessage.setCtiId(ctiId);
        ctimessage.setTaskCount(suit.getTaskCount() + 1);
        ctiMessageservice.updateByPrimaryKeySelective(ctimessage);

        return ResultUtil.success("0", "成功");
    }

    /**
     * 修改渐进式外呼接口
     *
     * @param params
     * @return
     */
    @Override
    public Result update(JSONObject params) {
        JSONObject JsonParams = params.getJSONObject("params");
        String serviceId = JsonParams.getString("serviceId");//任务短号
        String XfServiceId = "000001" + WSContent.companyNo + "11" + serviceId;//拼接后新方的任务号
        String vccId = JsonParams.getString("vccId");//集团号

        String beginTime1 = JsonParams.getString("beginTime1");
        String beginTime2 = JsonParams.getString("beginTime2");
        String beginTime3 = JsonParams.getString("beginTime3");

        CtiMessageExtends ctiMessageExtends = ctiMessageservice.queryCtimessageBytaskId(serviceId);
        if (ctiMessageExtends == null) {
            logger.error("没有找到任务号对应的cti");
            return ResultUtil.error("0", "没有找到任务号对应的cti");
        }
        String ctiIp = ctiMessageExtends.getCtiIp();
        JSONObject toCC = new JSONObject();

        if (!beginTime1.isEmpty() || !beginTime2.isEmpty() || !beginTime3.isEmpty()) {
            for (int i = 1; i <= 3; i++) {
                String beginTime = JsonParams.getString("beginTime" + i);
                String endTime = JsonParams.getString("endTime" + i);
                if (beginTime == null || beginTime.isEmpty()) {
                    continue;
                }
                if (endTime == null || endTime.isEmpty()) {
                    endTime = "23:59";
                }
                toCC.put("itemKey", serviceId + String.valueOf(i)); // 条目键
                toCC.put("scheduleKey", serviceId); // 日程键
                toCC.put("sunday", "1"); // 周日，0=无，1=有
                toCC.put("monday", "1"); // 周一，0=无，1=有
                toCC.put("tuesday", "1"); // 周二，0=无，1=有
                toCC.put("wednesday", "1"); // 周三，0=无，1=有
                toCC.put("thursday", "1"); // 周四，0=无，1=有
                toCC.put("friday", "1"); // 周五，0=无，1=有
                toCC.put("saturday", "1"); // 周六，0=无，1=有
                toCC.put("hourStart", beginTime.substring(0, 2)); // 开始小时
                toCC.put("hourEnd", endTime.substring(0, 2)); // 结束小时
                toCC.put("minuteStartminuteStart", beginTime.substring(3, 5)); // 开始分钟
                toCC.put("minuteEnd", endTime.substring(3, 5)); // 结束分钟
                toCC.put("updateKey", simpleSQL.cinNowTime()); // 更新标识
                WSRtnJsonCtx resultScheduleItem = clien.doPost(WSContent.vccUrl, ctiIp, "operateScheduleItem", WSContent._UPDATE, toCC);

                if (!"0".equals(resultScheduleItem.getRescode())) {
                    logger.error("修改第" + i + "条日程条目失败，返回的信息为：" + resultScheduleItem.getResJsonObj());
                    return ResultUtil.error("-9999", "修改日程条目失败");
                }
            }
        }
        WSRtnJsonCtx resultTask = clien.doPost(WSContent.servUrl, ctiIp, "operateHumanTask", WSContent._UPDATE, JsonParams);
        if (!"0".equals(resultTask.getRescode())) {
            logger.error("修改任务失败，返回的信息为：" + resultTask.getResJsonObj());
            return ResultUtil.error("-9999", "修改任务失败");
        }
        return ResultUtil.success("0", "成功");
    }

}
